<script>
// import Vue from 'vue';
// import { createEditor } from "@wangeditor/editor";
const { createEditor } = window.wangEditor
function genErrorInfo(fnName) {
  let info = `请使用 '@${fnName}' 事件，不要放在 props 中`;
  info += `\nPlease use '@${fnName}' event instead of props`;
  return info;
}

export default {
  // 【注意】单独写 <template>...</template> 时，rollup 打包完浏览器运行时报错，所以先在这里写 template
  render(h) {
    return h("div", { ref: "box" });
  },
  name: "Editor",
  data() {
    return {
      curValue: "",
      editor: null,
    };
  },
  props: [
    "defaultContent",
    "defaultConfig",
    "mode",
    "defaultHtml",
    "value",
    "readOnly",
  ], // value 用于自定义 v-model
  mounted() {
    this.create();
    setTimeout(() => {
      console.log(
        "000000000wang editor---readonly---->  mounted",
        this.editor,
        this.readOnly
      );
      if (!this.editor) return;
      if (this.readOnly) {
        this.editor.disable();
      } else {
        this.editor.enable();
      }
    }, 1);
  },
  watch: {
    readOnly(val) {
      // 使用 editor.enable() 和 editor.disable()来处理wang editor的readonly
      console.log(
        "000000000wang editor---readonly----> change",
        this.editor,
        val
      );
      if (!this.editor) return;
      if (val) {
        this.editor.disable();
      } else {
        this.editor.enable();
      }
    },
    // 监听 'value' 属性变化 - value 用于自定义 v-model
    value(newVal) {
      if (newVal === this.curValue) return; // 和当前内容一样，则忽略
      // 重置 HTML
      this.$nextTick(() => {
        this.setHtml(newVal);
      });
    },
  },
  beforeDestroy() {
    document.querySelector("#w-e-textarea-1") &&
      document
        .querySelector("#w-e-textarea-1")
        .removeEventListener("input", this.updateSelection);
  },
  methods: {
    // 重置 HTML
    setHtml(newHtml) {
      if (this.editor == null) return;
      console.log("this.editor", this.editor);
      this.$nextTick(() => {
        this.editor.setHtml(newHtml);
      });
    },
    updateSelection(e) {
      console.log("w-e-textarea-1 input");
      console.log("onInput");
      if (this.value === "") {
        // 如果是pc的话，timeout设置为5就好，ios经测试，使用40才有效果
        const timeout = 40;
        setTimeout(() => {
          const el = e.target;
          if (window.getSelection) {
            el.focus();
            const sel = getSelection();
            sel.selectAllChildren(el);
            sel.collapseToEnd();
          } else if (document.selection) {
            var range = document.selection.createRange(); // 创建选择对象
            range.moveToElementText(el); // range定位到el
            range.collapse(false); // 光标移至最后
            range.select();
          }
        }, timeout);
      }
    },
    // 创建 editor
    create() {
      if (this.$refs.box == null) return;

      const defaultConfig = this.defaultConfig || {};

      const defaultContent = JSON.stringify(
        Array.isArray(this.defaultContent) ? this.defaultContent : []
      );

      createEditor({
        selector: this.$refs.box,
        html: this.value || this.defaultHtml || "",
        config: {
          ...defaultConfig,
          onCreated: (editor) => {
            this.editor = Object.seal(editor); // 注意，一定要用 Object.seal() 否则会报错

            this.$emit("onCreated", editor);
            if (defaultConfig.onCreated) {
              const info = genErrorInfo("onCreated");
              throw new Error(info);
            }
          },
          onChange: (editor) => {
            let editorHtml = editor.getHtml();
            // 如果为空时, editor的内容是<p><br></p>, 需要替换
            editorHtml = editorHtml === "<p><br></p>" ? "" : editorHtml;
            this.curValue = editorHtml; // 记录当前 html 内容
            this.$emit("input", editorHtml); // 用于自定义 v-model

            this.$emit("onChange", editorHtml);
            if (defaultConfig.onChange) {
              const info = genErrorInfo("onChange");
              throw new Error(info);
            }
          },
          onDestroyed: (editor) => {
            this.$emit("onDestroyed", editor);
            if (defaultConfig.onDestroyed) {
              const info = genErrorInfo("onDestroyed");
              throw new Error(info);
            }
          },
          onMaxLength: (editor) => {
            this.$emit("onMaxLength", editor);
            if (defaultConfig.onMaxLength) {
              const info = genErrorInfo("onMaxLength");
              throw new Error(info);
            }
          },
          onFocus: (editor) => {
            this.$emit("onFocus", editor);
            if (defaultConfig.onFocus) {
              const info = genErrorInfo("onFocus");
              throw new Error(info);
            }
          },
          onBlur: (editor) => {
            this.$emit("onBlur", editor);
            if (defaultConfig.onBlur) {
              const info = genErrorInfo("onBlur");
              throw new Error(info);
            }
          },
          customAlert: (info, type) => {
            this.$emit("customAlert", info, type);
            if (defaultConfig.customAlert) {
              const info = genErrorInfo("customAlert");
              throw new Error(info);
            }
          },
          customPaste: (editor, event) => {
            if (defaultConfig.customPaste) {
              const info = genErrorInfo("customPaste");
              throw new Error(info);
            }
            let res;
            this.$emit("customPaste", editor, event, (val) => {
              res = val;
            });
            return res;
          },
        },
        content: JSON.parse(defaultContent),
        mode: this.mode || "default",
      });
      console.log("this.isMobile", this.isMobile);
      if (this.isMobile) {
        setTimeout(() => {
          console.log(
            "w-e-textarea-1 input",
            document.querySelector("#w-e-textarea-1")
          );
          document
            .querySelector("#w-e-textarea-1")
            .addEventListener("input", this.updateSelection);
        }, 300);
      }
    },
  },
};
</script>
